package com.daniel.gof.builder;

/**
 * 详细说明
 *
 * @author Daniel
 * @version V1.0
 * @date 2020/5/14 14:50
 */
public class Retrofit {
	// 下面是“一堆”的属性
	private String name;
	private String password;
	private String nickName;
	private int age;

	// 构造方法私有化，不然客户端就会直接调用构造方法了
	private Retrofit(Builder builder) {
		this.name = builder.name;
		this.password = builder.password;
		this.nickName = builder.nickName;
		this.age = builder.age;
	}

	@Override
	public String toString() {
		return "Retrofit{" +
				"name='" + name + '\'' +
				", password='" + password + '\'' +
				", nickName='" + nickName + '\'' +
				", age=" + age +
				'}';
	}

	// 静态方法，用于生成一个 Builder，这个不一定要有，不过写这个方法是一个很好的习惯，
	// 有些代码要求别人写 new User.UserBuilder().a()...build() 看上去就没那么好
	public static Builder builder() {
		return new Builder();
	}

	public static class Builder {
		// 下面是和 User 一模一样的一堆属性
		private String name;
		private String password;
		private String nickName;
		private int age;

		private Builder() {

		}

		// 链式调用设置各个属性值，返回 this
		public Builder setName(String name) {
			this.name = name;
			return this;
		}

		public Builder setPassword(String password) {
			this.password = password;
			return this;
		}

		public Builder setNickName(String nickName) {
			this.nickName = nickName;
			return this;
		}

		public Builder setAge(int age) {
			this.age = age;
			return this;
		}

		// build() 方法负责将Builder中设置好的属性“复制”到 Retrofit 中。
		// 当然，可以在 “复制” 之前做点检验
		public Retrofit build() {
			if (this.name == null || this.password == null) {
				throw new RuntimeException("用户名密码必填");
			}
			if (age <= 0 || age > 120) {
				throw new RuntimeException("年龄不合法");
			}
			// 还可以做赋予”默认值“的功能
			if (this.nickName == null) {
				nickName = name;
			}
			return new Retrofit(this);
		}
	}
}
